package Q2.dao.impl;

import Q2.dao.StudentDao;
import Q2.pojo.SQLConstant;
import Q2.pojo.Student;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.SneakyThrows;
import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * Student dao default implementation
 *
 * @author chisheng
 */
@AllArgsConstructor
public class StudentDaoMySQLImpl implements StudentDao {

    /**
     * A connection (session) with a specific database
     */
    private final Connection conn;

    @Override
    @SneakyThrows
    public boolean insertOne(@NonNull Student student) {
        PreparedStatement pstmt = null;

        try {
            conn.setAutoCommit(true);
            pstmt = conn.prepareStatement(SQLConstant.INSERT_STUDENT);
            pstmt.setString(1, student.getNo());
            pstmt.setString(2, student.getName());
            pstmt.setInt(3, student.getAge());
            pstmt.setDate(4, student.getBirthday());
            pstmt.setBlob(5, student.getPhoto());
            return pstmt.executeUpdate() > 0;
        } finally {
            JDBCUtils.close(pstmt, conn);
        }
    }

    @Override
    @SneakyThrows
    public boolean deleteByPrimaryKey(int id) {
        PreparedStatement pstmt = null;

        try {
            conn.setAutoCommit(true);
            pstmt = conn.prepareStatement(SQLConstant.DELETE_STUDENT);
            pstmt.setInt(0, id);
            return pstmt.executeUpdate() > 0;
        } finally {
            JDBCUtils.close(pstmt, conn);
        }
    }

    @Override
    @SneakyThrows
    public boolean updateByPrimaryKey(@NonNull Student student) {
        PreparedStatement pstmt = null;

        try {
            conn.setAutoCommit(true);
            pstmt = conn.prepareStatement(SQLConstant.UPDATE_STUDENT);
            return pstmt.executeUpdate() > 0;
        } finally {
            JDBCUtils.close(pstmt, conn);
        }
    }

    @Override
    @SneakyThrows
    public Student findByStudentNumber(@NonNull String number) {
        ResultSet resultSet = null;
        PreparedStatement pstmt = null;

        try {
            pstmt = conn.prepareStatement(SQLConstant.QUERY_STUDENT);
            pstmt.setString(0, number);
            resultSet = pstmt.executeQuery();
            return new Student(
                    resultSet.getInt("id"),
                    resultSet.getString("no"),
                    resultSet.getString("name"),
                    resultSet.getInt("age"),
                    resultSet.getDate("birthday"),
                    resultSet.getBlob("photo")
            );
        } finally {
            JDBCUtils.close(pstmt, conn, resultSet);
        }
    }

}
